
#include "jxos_public.h"
#include "bsp/bsp_key.h"
#include "../platform/N76E003/soc_common/Common/hal.h"

#define STATE_WAIT_TO_TIMMING	0
#define STATE_TIMMING_WAKE		1
#define STATE_TIMMING_SLEEP		2

void ir_send_pin_init(void);
void ir_send_pin_idle(void);
void ir_send_pin_pulse(void);
void ir_send_power_on(void);
void ir_send_power_off(void);
void ir_timer_init(void);
void ir_timer_run(void);
void key_pin_init(void);
uint8_t key_pin_read(uint8_t num);
void led_init(void);
void led_on(void);
void led_off(void);

extern uint8_t level_time_data[];
extern uint16_t level_time_data_len;

static uint16_t level_time_data_p;
static uint8_t busy_flag;
static uint16_t counter;
void ir_tx_tick_handler(void)
{
	if(busy_flag == 1){
		return;
	}
	
	if(counter > 0){
		counter--;
	}
	if(counter > 0){
		return;
	}
	
	if(level_time_data_p > level_time_data_len){
		ir_send_pin_idle();
		busy_flag = 1;
		return;
	}
	
	if((level_time_data[level_time_data_p]&0x80) != 0){
		ir_send_pin_pulse();
	}
	else{
		ir_send_pin_idle();
	}
	counter = level_time_data[level_time_data_p]&(~0x80);
	counter <<= 8;
	counter += level_time_data[level_time_data_p+1];	
	level_time_data_p += 2;
}

void ir_tx_send(void)
{
	level_time_data_p = 0;
	busy_flag = 0;
	counter = 0;
}

extern uint8_t rx_lock;
static void short_press(uint8_t key_num)
{
	if(rx_lock == 1){
		led_on();
		delay_1ms(250);
		led_off();
		ir_tx_send();
	}
}


static void long_press(uint8_t key_num)
{
	rx_lock = 0;
	led_on();
}

//static void ir_send_task(uint8_t task_id, void * parameter)
//{
//
//}

void ir_tx_task_init(void)
{
	ir_send_pin_init();
	
	led_init();
	led_off();
	
	bsp_key_init(key_pin_init, key_pin_read,
				0,
				0,
				short_press,
				long_press
				);
 
	ir_timer_init();
	ir_timer_run();
	ir_send_power_on();
	
	level_time_data_p = 0;
	busy_flag = 1;
	counter = 0;
	
//	jxos_task_create(ir_send_task, "ir_send", 0);
}